<?php
/*******************************************************************************
 * $Date:: Jan 7, 2011 3:43:44 PM                                              $
 * $Revision:                                                                  $
 * $Author:: Tuan Duong                                                        $
 * $Comment::                                                                  $
 ******************************************************************************/ 
/**
 * Description here...
 * 
 * @package Lua
 * @subpackage Application
 * @author Tuan Duong <tuan[at]smartdzine[dot]com>
 * @version 
 */

class Lua_Dispatcher implements Lua_Dispatcher_Interface
{
    public function dispatch(Lua_Router_Abstract $router)
    {
        try {
            $controller = $this->getControllerName($router);
            $action = $this->getActionName($router);
            if (!method_exists($controller, $action)) {
                throw new Lua_Exception('Action ' . $action . ' not found in ' . get_class($controller));
            }
            $controller->preDispatch();
            $controller->{$action}();
            $controller->render();
            $controller->postDispatch();
        } catch (Lua_Exception $ex) {
            include_once(APPLICATION_PATH . DS . $router->getModule() . DS . 'controllers' . DS . "ErrorController.php");
            $router->setController('error');
            $router->setAction('error');
            $errorController = new ErrorController();
            $errorController->setView(new Lua_View(new Zend_View()));
            $errorController->setParam('error', $ex);
            $errorController->errorAction();
            $errorController->render();
            exit();
//            echo get_class($ex) . " : " . $ex->getMessage();
//            echo '<pre>' . $ex->getTraceAsString() . '</pre>';
//            echo "<br />";
        }
    }

    /** 
     * (non-PHPdoc)
     * @see Lua_Dispatcher_Interface::getControllerName()
     */
    public function getControllerName(Lua_Router_Abstract $router)
    {
        $module = $router->getModule();
        $controlerPath = APPLICATION_PATH . DS . $module . DS . 'controllers';
        $controllerClass = ucfirst($router->getController()) . 'Controller';
        if (!file_exists($controlerPath . DS . $controllerClass . '.php')) {
            throw new Lua_Exception($controllerClass . ' not fould');
        } else {
            include_once $controlerPath . DS . $controllerClass . '.php';
        }
        return new $controllerClass();
    }

    /**
     * @param Lua_Router_Abstract $router
     * @return string
     */
    public function getActionName(Lua_Router_Abstract $router)
    {
        return Lua_Util_Common::toCamelCase($router->getAction(), false, true) . 'Action';
    }
    
}